﻿using System;
using USNetFramework.Utils;

namespace Crypt.Skynet
{
    public class Des
    {
        // private static int SMALL_CHUNK = 256;

        /* the eight DES S-boxes */

        private static uint[] SB1 = {
            0x01010400, 0x00000000, 0x00010000, 0x01010404,
            0x01010004, 0x00010404, 0x00000004, 0x00010000,
            0x00000400, 0x01010400, 0x01010404, 0x00000400,
            0x01000404, 0x01010004, 0x01000000, 0x00000004,
            0x00000404, 0x01000400, 0x01000400, 0x00010400,
            0x00010400, 0x01010000, 0x01010000, 0x01000404,
            0x00010004, 0x01000004, 0x01000004, 0x00010004,
            0x00000000, 0x00000404, 0x00010404, 0x01000000,
            0x00010000, 0x01010404, 0x00000004, 0x01010000,
            0x01010400, 0x01000000, 0x01000000, 0x00000400,
            0x01010004, 0x00010000, 0x00010400, 0x01000004,
            0x00000400, 0x00000004, 0x01000404, 0x00010404,
            0x01010404, 0x00010004, 0x01010000, 0x01000404,
            0x01000004, 0x00000404, 0x00010404, 0x01010400,
            0x00000404, 0x01000400, 0x01000400, 0x00000000,
            0x00010004, 0x00010400, 0x00000000, 0x01010004
        };

        private static uint[] SB2 = {
            0x80108020, 0x80008000, 0x00008000, 0x00108020,
            0x00100000, 0x00000020, 0x80100020, 0x80008020,
            0x80000020, 0x80108020, 0x80108000, 0x80000000,
            0x80008000, 0x00100000, 0x00000020, 0x80100020,
            0x00108000, 0x00100020, 0x80008020, 0x00000000,
            0x80000000, 0x00008000, 0x00108020, 0x80100000,
            0x00100020, 0x80000020, 0x00000000, 0x00108000,
            0x00008020, 0x80108000, 0x80100000, 0x00008020,
            0x00000000, 0x00108020, 0x80100020, 0x00100000,
            0x80008020, 0x80100000, 0x80108000, 0x00008000,
            0x80100000, 0x80008000, 0x00000020, 0x80108020,
            0x00108020, 0x00000020, 0x00008000, 0x80000000,
            0x00008020, 0x80108000, 0x00100000, 0x80000020,
            0x00100020, 0x80008020, 0x80000020, 0x00100020,
            0x00108000, 0x00000000, 0x80008000, 0x00008020,
            0x80000000, 0x80100020, 0x80108020, 0x00108000
        };

        private static uint[] SB3 = {
            0x00000208, 0x08020200, 0x00000000, 0x08020008,
            0x08000200, 0x00000000, 0x00020208, 0x08000200,
            0x00020008, 0x08000008, 0x08000008, 0x00020000,
            0x08020208, 0x00020008, 0x08020000, 0x00000208,
            0x08000000, 0x00000008, 0x08020200, 0x00000200,
            0x00020200, 0x08020000, 0x08020008, 0x00020208,
            0x08000208, 0x00020200, 0x00020000, 0x08000208,
            0x00000008, 0x08020208, 0x00000200, 0x08000000,
            0x08020200, 0x08000000, 0x00020008, 0x00000208,
            0x00020000, 0x08020200, 0x08000200, 0x00000000,
            0x00000200, 0x00020008, 0x08020208, 0x08000200,
            0x08000008, 0x00000200, 0x00000000, 0x08020008,
            0x08000208, 0x00020000, 0x08000000, 0x08020208,
            0x00000008, 0x00020208, 0x00020200, 0x08000008,
            0x08020000, 0x08000208, 0x00000208, 0x08020000,
            0x00020208, 0x00000008, 0x08020008, 0x00020200
        };

        private static uint[] SB4 = {
            0x00802001, 0x00002081, 0x00002081, 0x00000080,
            0x00802080, 0x00800081, 0x00800001, 0x00002001,
            0x00000000, 0x00802000, 0x00802000, 0x00802081,
            0x00000081, 0x00000000, 0x00800080, 0x00800001,
            0x00000001, 0x00002000, 0x00800000, 0x00802001,
            0x00000080, 0x00800000, 0x00002001, 0x00002080,
            0x00800081, 0x00000001, 0x00002080, 0x00800080,
            0x00002000, 0x00802080, 0x00802081, 0x00000081,
            0x00800080, 0x00800001, 0x00802000, 0x00802081,
            0x00000081, 0x00000000, 0x00000000, 0x00802000,
            0x00002080, 0x00800080, 0x00800081, 0x00000001,
            0x00802001, 0x00002081, 0x00002081, 0x00000080,
            0x00802081, 0x00000081, 0x00000001, 0x00002000,
            0x00800001, 0x00002001, 0x00802080, 0x00800081,
            0x00002001, 0x00002080, 0x00800000, 0x00802001,
            0x00000080, 0x00800000, 0x00002000, 0x00802080
        };

        private static uint[] SB5 = {
            0x00000100, 0x02080100, 0x02080000, 0x42000100,
            0x00080000, 0x00000100, 0x40000000, 0x02080000,
            0x40080100, 0x00080000, 0x02000100, 0x40080100,
            0x42000100, 0x42080000, 0x00080100, 0x40000000,
            0x02000000, 0x40080000, 0x40080000, 0x00000000,
            0x40000100, 0x42080100, 0x42080100, 0x02000100,
            0x42080000, 0x40000100, 0x00000000, 0x42000000,
            0x02080100, 0x02000000, 0x42000000, 0x00080100,
            0x00080000, 0x42000100, 0x00000100, 0x02000000,
            0x40000000, 0x02080000, 0x42000100, 0x40080100,
            0x02000100, 0x40000000, 0x42080000, 0x02080100,
            0x40080100, 0x00000100, 0x02000000, 0x42080000,
            0x42080100, 0x00080100, 0x42000000, 0x42080100,
            0x02080000, 0x00000000, 0x40080000, 0x42000000,
            0x00080100, 0x02000100, 0x40000100, 0x00080000,
            0x00000000, 0x40080000, 0x02080100, 0x40000100
        };

        private static uint[] SB6 = {
            0x20000010, 0x20400000, 0x00004000, 0x20404010,
            0x20400000, 0x00000010, 0x20404010, 0x00400000,
            0x20004000, 0x00404010, 0x00400000, 0x20000010,
            0x00400010, 0x20004000, 0x20000000, 0x00004010,
            0x00000000, 0x00400010, 0x20004010, 0x00004000,
            0x00404000, 0x20004010, 0x00000010, 0x20400010,
            0x20400010, 0x00000000, 0x00404010, 0x20404000,
            0x00004010, 0x00404000, 0x20404000, 0x20000000,
            0x20004000, 0x00000010, 0x20400010, 0x00404000,
            0x20404010, 0x00400000, 0x00004010, 0x20000010,
            0x00400000, 0x20004000, 0x20000000, 0x00004010,
            0x20000010, 0x20404010, 0x00404000, 0x20400000,
            0x00404010, 0x20404000, 0x00000000, 0x20400010,
            0x00000010, 0x00004000, 0x20400000, 0x00404010,
            0x00004000, 0x00400010, 0x20004010, 0x00000000,
            0x20404000, 0x20000000, 0x00400010, 0x20004010
        };

        private static uint[] SB7 = {
            0x00200000, 0x04200002, 0x04000802, 0x00000000,
            0x00000800, 0x04000802, 0x00200802, 0x04200800,
            0x04200802, 0x00200000, 0x00000000, 0x04000002,
            0x00000002, 0x04000000, 0x04200002, 0x00000802,
            0x04000800, 0x00200802, 0x00200002, 0x04000800,
            0x04000002, 0x04200000, 0x04200800, 0x00200002,
            0x04200000, 0x00000800, 0x00000802, 0x04200802,
            0x00200800, 0x00000002, 0x04000000, 0x00200800,
            0x04000000, 0x00200800, 0x00200000, 0x04000802,
            0x04000802, 0x04200002, 0x04200002, 0x00000002,
            0x00200002, 0x04000000, 0x04000800, 0x00200000,
            0x04200800, 0x00000802, 0x00200802, 0x04200800,
            0x00000802, 0x04000002, 0x04200802, 0x04200000,
            0x00200800, 0x00000000, 0x00000002, 0x04200802,
            0x00000000, 0x00200802, 0x04200000, 0x00000800,
            0x04000002, 0x04000800, 0x00000800, 0x00200002
        };

        private static uint[] SB8 = {
            0x10001040, 0x00001000, 0x00040000, 0x10041040,
            0x10000000, 0x10001040, 0x00000040, 0x10000000,
            0x00040040, 0x10040000, 0x10041040, 0x00041000,
            0x10041000, 0x00041040, 0x00001000, 0x00000040,
            0x10040000, 0x10000040, 0x10001000, 0x00001040,
            0x00041000, 0x00040040, 0x10040040, 0x10041000,
            0x00001040, 0x00000000, 0x00000000, 0x10040040,
            0x10000040, 0x10001000, 0x00041040, 0x00040000,
            0x00041040, 0x00040000, 0x10041000, 0x00001000,
            0x00000040, 0x10040040, 0x00001000, 0x00041040,
            0x10001000, 0x00000040, 0x10000040, 0x10040000,
            0x10040040, 0x10000000, 0x00040000, 0x10001040,
            0x00000000, 0x10041040, 0x00040040, 0x10000040,
            0x10040000, 0x10001000, 0x10001040, 0x00000000,
            0x10041040, 0x00041000, 0x00041000, 0x00001040,
            0x00001040, 0x00040040, 0x10000000, 0x10041000
        };

        /* PC1: left and right halves bit-swap */
        private static uint[] LHs = {
            0x00000000, 0x00000001, 0x00000100, 0x00000101,
            0x00010000, 0x00010001, 0x00010100, 0x00010101,
            0x01000000, 0x01000001, 0x01000100, 0x01000101,
            0x01010000, 0x01010001, 0x01010100, 0x01010101
        };

        private static uint[] RHs = {
            0x00000000, 0x01000000, 0x00010000, 0x01010000,
            0x00000100, 0x01000100, 0x00010100, 0x01010100,
            0x00000001, 0x01000001, 0x00010001, 0x01010001,
            0x00000101, 0x01000101, 0x00010101, 0x01010101,
        };


        /* Initial Permutation macro */
        private static void DES_IP(ref uint X, ref uint Y, ref uint T)
        {
	        T = ((X >>  4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T <<  4);
	        T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16);
	        T = ((Y >>  2) ^ X) & 0x33333333; X ^= T; Y ^= (T <<  2);
	        T = ((Y >>  8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T <<  8);
	        Y = ((Y << 1) | (Y >> 31)) & 0xFFFFFFFF;
	        T = (X ^ Y) & 0xAAAAAAAA; Y ^= T; X ^= T;
	        X = ((X << 1) | (X >> 31)) & 0xFFFFFFFF;
        }

        /* Final Permutation macro */
        private static void DES_FP(ref uint X, ref uint Y, ref uint T)
        {
	        X = ((X << 31) | (X >> 1)) & 0xFFFFFFFF;
	        T = (X ^ Y) & 0xAAAAAAAA; X ^= T; Y ^= T;
	        Y = ((Y << 31) | (Y >> 1)) & 0xFFFFFFFF;
	        T = ((Y >>  8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T <<  8);
	        T = ((Y >>  2) ^ X) & 0x33333333; X ^= T; Y ^= (T <<  2);
	        T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16);
	        T = ((X >>  4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T <<  4);
        }

        /* DES round macro */
        private static void DES_ROUND(ref uint X, ref uint Y, ref uint T, uint[] SK, ref uint idx)
        {
	        T = (SK[idx++]) ^ X;
	        Y ^= SB8[(T      ) & 0x3F] ^
		         SB6[(T >>  8) & 0x3F] ^
		         SB4[(T >> 16) & 0x3F] ^
		         SB2[(T >> 24) & 0x3F];

	        T = (SK[idx++]) ^ ((X << 28) | (X >> 4));
	        Y ^= SB7[(T      ) & 0x3F] ^
		         SB5[(T >>  8) & 0x3F] ^
		         SB3[(T >> 16) & 0x3F] ^
		         SB1[(T >> 24) & 0x3F];
        }

        private static void _des_crypt(uint[] SK, byte[] input, int inoffset, ref byte[] output, int outoffset) 
        {
	        uint X, Y, T;

            X =   ((uint)input[inoffset+0] << 24)
                | ((uint)input[inoffset+1] << 16)
                | ((uint)input[inoffset+2] <<  8)
                | ((uint)input[inoffset+3]);
            Y =   ((uint)input[inoffset+4] << 24)
                | ((uint)input[inoffset+5] << 16)
                | ((uint)input[inoffset+6] <<  8)
                | ((uint)input[inoffset+7]);

            T = 0;

            DES_IP(ref X, ref Y, ref T);

            uint idx = 0;
            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            DES_ROUND(ref Y, ref X, ref T, SK, ref idx);    DES_ROUND(ref X, ref Y, ref T, SK, ref idx);

            if (32 != idx)
                Log.WriteInfo("Error des round %d, need 32", idx);

            DES_FP(ref Y, ref X, ref T);


            output[outoffset+0] = (byte)((Y >> 24) & 0xff);
            output[outoffset+1] = (byte)((Y >> 16) & 0xff);
            output[outoffset+2] = (byte)((Y >>  8) & 0xff);
            output[outoffset+3] = (byte)((Y      ) & 0xff);
            output[outoffset+4] = (byte)((X >> 24) & 0xff);
            output[outoffset+5] = (byte)((X >> 16) & 0xff);
            output[outoffset+6] = (byte)((X >>  8) & 0xff);
            output[outoffset+7] = (byte)((X      ) & 0xff);
        }

        public static byte[] Encrypt(byte[] toEncrypt, byte[] inKey)
        {
            uint[] sk = _des_key(inKey);

            int textsz = toEncrypt.Length;
            int chunksz = (textsz + 8) & ~7;
            // chunksz = chunksz < SMALL_CHUNK ? SMALL_CHUNK : chunksz;
            byte[] buffer = new byte[chunksz];

            int i;
            for (i = 0; i < textsz - 7; i += 8)
            {
                _des_crypt(sk, toEncrypt, i, ref buffer, i);
            }

            int bytes = textsz - i;
            byte[] tail = new byte[8];
            int j;
            for (j = 0; j < 8; j++)
            {
                if (j < bytes)
                {
                    tail[j] = toEncrypt[i + j];
                }
                else if (j == bytes)
                {
                    tail[j] = 0x80;
                }
                else
                {
                    tail[j] = 0;
                }
            }

            _des_crypt(sk, tail, 0, ref buffer, i);

            return buffer;
        }

        public static byte[] Decrypt(byte[] toDecrypt, byte[] inKey)
        {
            uint[] esk = _des_key(inKey);
            uint[] sk = new uint[32];

            int i;
            for (i = 0; i < 32; i += 2)
            {
                sk[i] = esk[30 - i];
                sk[i + 1] = esk[31 - i];
            }

            int textsz = toDecrypt.Length;
            //textsz = textsz < SMALL_CHUNK ? SMALL_CHUNK : textsz;
            if ((textsz & 7) > 0 || textsz == 0)
            {
                Log.WriteInfo("Invalid des crypt text length %d", textsz);
                return null;
            }

            byte[] buffer = new byte[textsz];

            for (i = 0; i < textsz; i += 8)
            {
                _des_crypt(sk, toDecrypt, i, ref buffer, i);
            }

            int padding = 1;
            for (i = textsz - 1; i >= textsz - 8; i--)
            {
                if (buffer[i] == 0)
                {
                    padding++;
                }
                else if (buffer[i] == 0x80)
                {
                    break;
                }
                else
                {
                    Log.WriteInfo("Invalid des crypt text");
                    return null;
                }
            }

            if (padding > 8)
            {
                Log.WriteInfo("Invalid des crypt text");
                return null;
            }

            byte[] result = new byte[textsz - padding];
            Buffer.BlockCopy(buffer, 0, result, 0, result.Length);

            return result;
        }

        private static uint[] _des_key(byte[] key)
        {
            if (8 != key.Length)
            {
                Log.WriteInfo("Invalid key size %d, need 8 bytes", key.Length);
                return null;
            }
            uint[] sk = new uint[32];
            uint X, Y, T;

            X =   ((uint)key[0] << 24)
                | ((uint)key[1] << 16)
                | ((uint)key[2] << 8)
                | ((uint)key[3]);
            Y =   ((uint)key[4] << 24)
                | ((uint)key[5] << 16)
                | ((uint)key[6] << 8)
                | ((uint)key[7]);

            /* Permuted Choice 1 */
            T = ((Y >> 4) ^ X) & 0x0F0F0F0F; X ^= T; Y ^= (T << 4);
            T = ((Y     ) ^ X) & 0x10101010; X ^= T; Y ^= (T     );

            X =   (LHs[(X      ) & 0xF] << 3) | (LHs[(X >>  8) & 0xF] << 2)
                | (LHs[(X >> 16) & 0xF] << 1) | (LHs[(X >> 24) & 0xF]     )
                | (LHs[(X >>  5) & 0xF] << 7) | (LHs[(X >> 13) & 0xF] << 6)
                | (LHs[(X >> 21) & 0xF] << 5) | (LHs[(X >> 29) & 0xF] << 4);

            Y =   (RHs[(Y >>  1) & 0xF] << 3) | (RHs[(Y >>  9) & 0xF] << 2)
                | (RHs[(Y >> 17) & 0xF] << 1) | (RHs[(Y >> 25) & 0xF]     )
                | (RHs[(Y >>  4) & 0xF] << 7) | (RHs[(Y >> 12) & 0xF] << 6)
                | (RHs[(Y >> 20) & 0xF] << 5) | (RHs[(Y >> 28) & 0xF] << 4);

            X &= 0x0FFFFFFF;
            Y &= 0x0FFFFFFF;

            /* calculate subkeys */
            int i;
            int idx = 0;
            for (i = 0; i < 16; i++)
            {
                if (i < 2 || i == 8 || i == 15)
                {
                    X = ((X << 1) | (X >> 27)) & 0x0FFFFFFF;
                    Y = ((Y << 1) | (Y >> 27)) & 0x0FFFFFFF;
                }
                else
                {
                    X = ((X << 2) | (X >> 26)) & 0x0FFFFFFF;
                    Y = ((Y << 2) | (Y >> 26)) & 0x0FFFFFFF;
                }

                sk[idx++] = ((X <<  4) & 0x24000000) | ((X << 28) & 0x10000000)
                          | ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000)
                          | ((X <<  6) & 0x01000000) | ((X <<  9) & 0x00200000)
                          | ((X >>  1) & 0x00100000) | ((X << 10) & 0x00040000)
                          | ((X <<  2) & 0x00020000) | ((X >> 10) & 0x00010000)
                          | ((Y >> 13) & 0x00002000) | ((Y >>  4) & 0x00001000)
                          | ((Y <<  6) & 0x00000800) | ((Y >>  1) & 0x00000400)
                          | ((Y >> 14) & 0x00000200) | ((Y      ) & 0x00000100)
                          | ((Y >>  5) & 0x00000020) | ((Y >> 10) & 0x00000010)
                          | ((Y >>  3) & 0x00000008) | ((Y >> 18) & 0x00000004)
                          | ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001);

                sk[idx++] = ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000)
                          | ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000)
                          | ((X >>  2) & 0x02000000) | ((X <<  1) & 0x01000000)
                          | ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000)
                          | ((X <<  3) & 0x00080000) | ((X >>  6) & 0x00040000)
                          | ((X << 15) & 0x00020000) | ((X >>  4) & 0x00010000)
                          | ((Y >>  2) & 0x00002000) | ((Y <<  8) & 0x00001000)
                          | ((Y >> 14) & 0x00000808) | ((Y >>  9) & 0x00000400)
                          | ((Y      ) & 0x00000200) | ((Y <<  7) & 0x00000100)
                          | ((Y >>  7) & 0x00000020) | ((Y >>  3) & 0x00000011)
                          | ((Y <<  2) & 0x00000004) | ((Y >> 21) & 0x00000002);
            }

            if (32 != idx)
                Log.WriteInfo("Error Sub key round %d, need 32", idx);

            return sk;
        }
    }
}